<template>
  <div class="traffic">
    <!-- <h3 class="box-title">
      <span>{{$t('traffic')}}</span>
    </h3> -->
    <div class="traffic-box space-y-10">
      <div class="traffic-bar"
        v-if="traffic && traffic.estimated_monthly_visits && JSON.stringify(traffic.estimated_monthly_visits)!=='{}'">
        <h3 class="traffic-title">
          {{$t('visitOverTime')}}
        </h3>
        <div class="traffic-info">
          <div class="traffic-table-box">
            <div class="traffic-table">
              <div class="traffic-td">
                <div class="traffic-tleft">
                  <span>{{$t('monthlyVisitLabel')}}</span>
                </div>
                <div class="traffic-tright">
                  <span>{{ Number(engagments.visits) | vResetVisit}}</span>
                </div>
              </div>
              <div class="traffic-td">
                <div class="traffic-tleft">
                  <span>{{$t('avgVisitDurationLabel')}}</span>
                </div>
                <div class="traffic-tright">
                  <span>{{Number(engagments.time_on_site) | formatTimeDuration}}</span>
                </div>
              </div>
              <div class="traffic-td">
                <div class="traffic-tleft">
                  <span>{{$t('pagePerVisitLabel')}}</span>
                </div>
                <div class="traffic-tright">
                  <span>{{Number(engagments.page_per_visit).toFixed(2)}}</span>
                </div>
              </div>
              <div class="traffic-td">
                <div class="traffic-tleft">
                  <span>{{$t('bounceRateLabel')}}</span>
                </div>
                <div class="traffic-tright">
                  <span>{{ Number(engagments.bounce_rate * 100).toFixed(2) }}%</span>
                </div>
              </div>
            </div>
          </div>
          <div class="traffic-chart-box m-t">
            <div class="date"
              v-if="dataRange && dataRange.length===2">
              <svg-icon iconName="adschedule_default" />
              <span>{{dataRange[0]}} - {{dataRange[1]}}&nbsp;{{$t('allTraffic')}}</span>
            </div>
            <no-ssr>
              <line-chart :chartData="estimated_monthly_visits_list"></line-chart>
            </no-ssr>
          </div>
        </div>
      </div>
      <div class="traffic-bar"
        v-if="traffic && traffic.top_country_shares && JSON.stringify(traffic.top_country_shares)!=='{}' && JSON.stringify(traffic.top_country_shares)!=='[]' && traffic.top_country_shares.length >0">
        <h3 class="traffic-title">
          {{$t('geography')}}
        </h3>
        <div class="traffic-info">
          <div class="traffic-table-box">
            <p class="t-desc">{{$t('top5Countries', {countriesNum: topCountryShares ? topCountryShares.length: 0})}}</p>
            <div class="traffic-table">
              <div class="traffic-td"
                v-for="(item, key) in topCountryShares"
                :key="item.country">
                <div class="traffic-tleft">
                  <div class="flag">
                    <img :src="getImage(item.two_code)"
                      alt=""
                      srcset="">
                  </div>
                  <span>{{item.two_code | fLabel(countries)}}</span>
                </div>
                <div class="traffic-tright">
                  <span>{{ Number(item.value * 100).toFixed(2) }}%</span>
                </div>
              </div>
            </div>
          </div>
          <div class="traffic-chart-box m-t">
            <div class="date"
              v-if="dataRange && dataRange.length===2">
              <svg-icon iconName="adschedule_default" />
              <span>{{dataRange[0]}} - {{dataRange[1]}}&nbsp;{{$t('desktopOnly')}}</span>
            </div>
            <no-ssr>
              <world-chart :chartData="topCountryShares"></world-chart>
            </no-ssr>
          </div>
        </div>
      </div>
      <div class="traffic-bar"
        v-if="traffic && traffic.traffic_sources && JSON.stringify(traffic.traffic_sources)!=='{}' && echartRing.total">
        <h3 class="traffic-title">
          {{$t('trafficSources')}}
        </h3>
        <div class="traffic-info">
          <div class="traffic-table-box">
            <div class="traffic-table">
              <div class="traffic-td"
                v-for="(item, key) in echartRing.data"
                :key="item.label">
                <div class="traffic-tleft">
                  <i class="dot"
                    :style="{ background: echartRing.colorsObj[item.labelKey] }"></i>
                  <span>{{ item.label }}</span>
                </div>
                <div class="traffic-tright">
                  <span>{{ `${((item.value / echartRing.total) * 100).toFixed(2)}%` }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="traffic-chart-box m-t">
            <div class="date"
              v-if="dataRange && dataRange.length===2">
              <svg-icon iconName="adschedule_default" />
              <span>{{dataRange[0]}} - {{dataRange[1]}}&nbsp;{{$t('worldwideDesktopOnly')}}</span>
            </div>
            <no-ssr>
              <ring-chart :chartData="echartRing"></ring-chart>
            </no-ssr>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  name: 'Traffic',
  props: {
    traffic: {
      type: Object | null,
      default() {
        return {}
      },
    },
  },
  watch: {
    traffic: {
      handler: function (val) {
        if (val) {
          let total = 0
          if (this.traffic.traffic_sources) {
            for (let key in this.traffic.traffic_sources) {
              if (this.traffic.traffic_sources[key] === null) {
                this.traffic.traffic_sources[key] = 0
              }
              total = total + this.traffic.traffic_sources[key]
            }
            this.echartRing.total = total

            let arr = []
            for (let key in this.traffic.traffic_sources) {
              arr.push({
                labelKey: key,
                label: this.fI18n(key),
                value: this.traffic.traffic_sources[key],
              })
            }
            this.echartRing.data = arr.sort((a, b) => {
              return b.value - a.value
            })
          }

          this.topCountryShares = this.traffic.top_country_shares
          this.estimated_monthly_visits = this.traffic.estimated_monthly_visits
          this.estimated_monthly_visits_list =
            this.traffic.estimated_monthly_visits_list
          this.engagments = this.traffic.engagments
          if (
            val &&
            val.estimated_monthly_visits_list &&
            val.estimated_monthly_visits_list.length
          ) {
            this.dataRange[0] = this.formattedDate(
              this.traffic.estimated_monthly_visits_list[0].date
            )
            this.dataRange[1] = this.formattedDate(
              this.traffic.estimated_monthly_visits_list[
                val.estimated_monthly_visits_list.length - 1
              ].date
            )
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      engagments: {},
      estimated_monthly_visits: {},
      estimated_monthly_visits_list: [],
      TopCountryShares: [],
      echartRing: {
        colors: [
          '#FF5384',
          '#1E75FF',
          '#0DD6F7',
          '#F9C019',
          '#08C87C',
          '#11A683',
        ],
        colorsObj: {
          Direct: '#FF5384',
          Mail: '#1E75FF',
          'Paid Referrals': '#0DD6F7',
          Referrals: '#F9C019',
          Search: '#08C87C',
          Social: '#11A683',
        },
        total: 0,
        data: {},
      },
      dataRange: [],
    }
  },
  computed: {
    ...mapState({
      countries: (state) => state.countries,
    }),
  },
  filters: {
    fLabel: function (val, options) {
      let obj = options.find((item) => {
        return val.toLowerCase() === item.value.toLowerCase()
      })
      if (obj && obj.label) {
        return obj.label
      } else {
        return val
      }
    },
    vResetVisit: function (val) {
      if (typeof val === 'number' && !isNaN(val)) {
        if (val < 5000) {
          return '< 5K'
        } else if (val >= 5000 && val < 1000000) {
          return (val / 1000).toFixed(1) + 'K'
        } else if (val >= 1000000 && val < 1000000000) {
          return (val / 1000000).toFixed(1) + 'M'
        } else {
          return (val / 1000000000).toFixed(1) + 'B'
        }
      } else {
        return '< 5K'
      }
    },
    formatTimeDuration: function (msTime) {
      //毫秒转换成时分秒展示
      let time = msTime
      let hour = Math.floor(time / 60 / 60)
      hour = hour.toString().padStart(2, '0')
      let minute = Math.floor(time / 60) % 60
      minute = minute.toString().padStart(2, '0')
      let second = Math.floor(time) % 60
      second = second.toString().padStart(2, '0')
      return `${hour}:${minute}:${second}`
    },
  },
  methods: {
    fI18n(arg) {
      const hasKey = this.$i18n.t(arg)
      if (hasKey) {
        const result = this.$i18n.t(arg)
        return result
      }
      return arg
    },
    formattedDate: function (val) {
      let values = ''
      if (val) {
        let monthArray = [
          'Jan',
          'Feb',
          'Mar',
          'Apr',
          'May',
          'Jun',
          'Jul',
          'Aug',
          'Sep',
          'Oct',
          'Nov',
          'Dec',
        ]

        let sDateArry = val.split('-')

        let sMonth = monthArray[parseInt(sDateArry[1] - 1)]
        values = sMonth + ' ' + sDateArry[0]
        return values
      } else {
        return ''
      }
    },
    //判断是否有国旗
    getImage(name) {
      try {
        const image = require('@/static/images/flags/' + name + '.png')
        if (image) {
          return image
        } else {
          return ''
        }
      } catch (error) {
        //console.log(error)
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.traffic {
  background: #ffffff;
  overflow: hidden;
  .box-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    span {
      flex: 1;
      font-size: 20px;
      font-weight: bold;
      color: #2f3032;
      line-height: 24px;
    }
  }
  .traffic-box {
    margin: 0 auto;
    .traffic-bar {
      .traffic-title {
        position: relative;
        font-size: 18px;
        font-weight: bold;
        color: #191919;
        line-height: 24px;
        padding-left: 18px;
        &::after {
          position: absolute;
          content: '';
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 5px;
          height: 20px;
          background: #2184fd;
          border-radius: 1px;
        }
      }
      .traffic-info {
        display: flex;
        align-items: flex-start;
        padding: 20px 0 20px 45px;
        .traffic-table-box {
          width: 33.3333%;
          flex-shrink: 0;
          margin-right: 100px;
          .t-desc {
            font-size: 16px;
            font-weight: 500;
            color: #191919;
            line-height: 20px;
            margin-bottom: 12px;
          }
          .traffic-table {
            background: #ffffff;
            border-radius: 6px;
            border: 1px solid #e5e5e5;
            padding: 0 22px;
            .traffic-td {
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding: 14px 0;
              .traffic-tleft {
                display: flex;
                align-items: center;
                font-size: 0;
                span {
                  font-size: 16px;
                  color: #191919;
                  line-height: 20px;
                }
                .flag {
                  width: 31px;
                  height: 18px;
                  margin-right: 12px;
                  img {
                    width: 31px;
                    height: 18px;
                  }
                }
                .dot {
                  display: block;
                  width: 12px;
                  height: 12px;
                  border-radius: 50%;
                  margin-right: 12px;
                }
              }
              .traffic-tright {
                span {
                  font-size: 16px;
                  font-weight: bold;
                  color: #191919;
                  line-height: 20px;
                }
              }
              & + .traffic-td {
                border-top: 1px solid #e5e5e5;
              }
            }
          }
        }
        .traffic-chart-box {
          flex: 1;
          &.m-t {
            margin-top: -42px;
          }
          .date {
            display: flex;
            align-items: center;
            margin-bottom: 12px;
            svg {
              font-size: 18px;
              margin-right: 8px;
              margin-top: -2px;
            }
            span {
              font-size: 16px;
              color: #191919;
              line-height: 20px;
            }
          }
        }
      }
      &:last-child {
        .traffic-info {
          padding-bottom: 0;
        }
      }
    }
  }
}
@media only screen and (max-width: 800px) {
  .traffic {
    .traffic-box {
      .traffic-bar {
        .traffic-info {
          display: block;
          padding: 20px 0 20px 2px;
          .traffic-table-box {
            width: 100%;
            margin-right: 0;
          }
          .traffic-chart-box.m-t {
            margin-top: 20px;
          }
        }
      }
    }
  }
}
</style>
